﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Forms;
using DICOMViewer.Utility;
using Newtonsoft.Json;
using xDataSet;

namespace IncoolReg
{
    public class OnlineForm : MainForm
    {
        protected override void form_init()
        {
            base.form_init();
            var i = 0;
            //判断是否联网
            if (!Program.InternetGetConnectedState(out i, 0))
            {
                MessageBox.Show("本设备当前未联网！请联网后重新打开程序！");
                Application.Exit();
                return;
            }
            //判断是否存在已经登记过的记录，如果记录已经存在的话，直接显示即可
            if (TryGetDataOnlineByHardWareCode()) return;
            //没有记录则初始化登记界面
            InitFromOnlineData();
            Shown += OnlineForm_Shown;
        }

        private void OnlineForm_Shown(object sender, EventArgs e)
        {
            getDataTask = new Task(() => { GetData(); });
            getDataTask.Start();
        }

        private void GetData()
        {
            //获取公司数据
            var companyList = GetProvinceData();
            var hospitalList = new List<Hashtable>();
            var officeList = new List<Hashtable>();
            foreach (Hashtable company in companyList)
            {
                //获取公司下医院信息
                xDataSet.xDataSet mRetHospital = new xDataSet.xDataSet("Weixin_Interface_User", "dev",
                    "getHospitalByCompanyUUID",
                    new[] {new xParameter("uuid", company["uuid"])}, Program.G_xDataSetConfigInterface);

                //判断返回值是否正确
                if (mRetHospital.SRetJObject["success"].ToString().ToLower() == "true")
                {
                    var hoptemp =
                        JsonConvert.DeserializeObject<List<Hashtable>>(mRetHospital.SRetJObject["body"].ToString());
                    foreach (Hashtable hop in hoptemp)
                    {
                        hop["zuzhiId"] = company["uuid"];
                        xDataSet.xDataSet mRetOfficel =
                            new xDataSet.xDataSet("Weixin_Interface_User", "dev",
                                "getOfficMsgByHospUUID",
                                new[] {new xParameter("uuid", hop["uuid"])}, Program.G_xDataSetConfigInterface);
                        if (mRetOfficel.SRetJObject["success"].ToString().ToLower() == "true")
                        {
                            var officetemp =
                                JsonConvert.DeserializeObject<List<Hashtable>>(
                                    mRetOfficel.SRetJObject["body"].ToString());
                            foreach (Hashtable off in officetemp)
                            {
                                off["hospitalId"] = hop["uuid"];
                            }
                            officeList.AddRange(officetemp);
                        }
                    }
                    hospitalList.AddRange(hoptemp);
                }
            }
            SerializeHelper.SerializeToJsonFile(hospitalList, string.Format(dataXmlSavePathFormat, "hospital.json"));
            SerializeHelper.SerializeToJsonFile(officeList, string.Format(dataXmlSavePathFormat, "office.json"));
        }

        protected override bool SaveEquipmentData()
        {
            xDataSet.xDataSet mRetDep = new xDataSet.xDataSet("Weixin_Interface_User", "dev", "addEquipment",
                new[]
                {
                    new xParameter("equipment_id", txt_sn.Text),
                    new xParameter("equipment",
                        string.IsNullOrEmpty(txt_name.Text.Trim()) ? "未命名" : txt_name.Text.Trim()),
                    new xParameter("province_id", mProvinceId),
                    new xParameter("province_name", mProvinceName),
                    new xParameter("city_id", mCityId),
                    new xParameter("city_name", mCityName),
                    new xParameter("area_id", mAreaId),
                    new xParameter("area_name", mAreaName),
                    new xParameter("zuzhi_id", mZuzhiId),
                    new xParameter("zuzhi_name", mZuzhiName),
                    new xParameter("department_category_id", mDepartmentId),
                    new xParameter("department_category_name", mDepartmentName),
                    new xParameter("hospitail_id", mHospitailId),
                    new xParameter("hospitail_name", mHospitailName),
                    new xParameter("office_id", mOfficeId),
                    new xParameter("office_name", mOfficeName)
                }, Program.G_xDataSetConfigInterface)
                ;
            return mRetDep.SRetJObject["success"].ToString().ToLower() == "true";
        }


        private bool TryGetDataOnlineByHardWareCode()
        {
            xDataSet.xDataSet mRetGetEquipment = new xDataSet.xDataSet("Weixin_Interface_User", "dev",
                "getEquipmentByEqID",
                new[] {new xParameter("id", txt_sn.Text)}, Program.G_xDataSetConfigInterface);

            if (mRetGetEquipment.SRet)
            {
                //信息存在，显示这个机器的信息
                cb_ok.Visible = false;
                //List<Hashtable> mRetListGetEquipment = JsonConvert.DeserializeObject<List<Hashtable>>(mRetGetEquipment.SRetJObject["body"].ToString());
                //Hashtable mRetListGetEquipment = JsonConvert.DeserializeObject<Hashtable>(mRetGetEquipment.SRetJObject["body"].ToString());
                txt_name.Text = mRetGetEquipment.SRetJObject["body"]["equipmentName"].ToString();
                txt_name.Enabled = false;

                cmb_zhuzi.DropDownStyle = ComboBoxStyle.DropDown;
                cmb_zhuzi.Text = mRetGetEquipment.SRetJObject["body"]["zuzhiName"].ToString();
                cmb_zhuzi.Enabled = false;

                cmb_hospital.DropDownStyle = ComboBoxStyle.DropDown;
                cmb_hospital.Text = mRetGetEquipment.SRetJObject["body"]["hospitalName"].ToString();
                cmb_hospital.Enabled = false;

                cmb_dep.DropDownStyle = ComboBoxStyle.DropDown;
                cmb_dep.Text = mRetGetEquipment.SRetJObject["body"]["deparmentCategoryName"].ToString();
                cmb_dep.Enabled = false;

                cmb_office.DropDownStyle = ComboBoxStyle.DropDown;
                cmb_office.Text = mRetGetEquipment.SRetJObject["body"]["officeName"].ToString();
                cmb_office.Enabled = false;

                cmb_province.Text = mRetGetEquipment.SRetJObject["body"]["provinceName"].ToString();
                cmb_province.Enabled = false;

                cmb_city.Text = mRetGetEquipment.SRetJObject["body"]["cityName"].ToString();
                cmb_city.Enabled = false;

                cmb_area.Text = mRetGetEquipment.SRetJObject["body"]["areaName"].ToString();
                cmb_area.Enabled = false;
                return true;
            }
            return false;
        }

        private void InitFromOnlineData()
        {
            //获取省区公司数据
            var comResult = GetProvinceData();
            //初始化省区公司下拉菜单
            if (comResult != null) InitProvinceControl(comResult);
            //获取科室类别数据
            comResult = GetDepartmentData();
            //初始化科室类别下拉菜单
            if (comResult != null) InitDepartmentControl(comResult);
        }

        protected override List<Hashtable> GetDepartmentData()
        {
            //获取所有科室类别的数据
            xDataSet.xDataSet mRetDep = new xDataSet.xDataSet("Weixin_Interface_User", "dev", "getAllDepartment",
                new xParameter[] {}, Program.G_xDataSetConfigInterface);
            //判断返回值是否正确
            if (mRetDep.SRetJObject["success"].ToString().ToLower() == "true")
            {
                var mRetList =
                    JsonConvert.DeserializeObject<List<Hashtable>>(mRetDep.SRetJObject["body"].ToString());
                return mRetList;
            }
            return null;
        }

        protected override List<Hashtable> GetProvinceData()
        {
            //获取省份的数据
             xDataSet.xDataSet mRet = new xDataSet.xDataSet("Weixin_Interface_User", "dev", "getAllZuZhi",
                new[] {new xParameter("id", 1)}, Program.G_xDataSetConfigInterface);//判断返回值是否正确 
            if (mRet.SRetJObject["success"].ToString().ToLower() == "true")
            {
                //保存获取的数据
                SaveJsonFile(mRet.SRetJObject["body"].ToString(), "zuzhi.json");
                var provinceList =
                    JsonConvert.DeserializeObject<List<Hashtable>>(mRet.SRetJObject["body"].ToString());
                return provinceList;
            }
            return null;
        }

        protected override List<Hashtable> GetHospitalDataByCompanyUuid(string companyUuid)
        {
            //获取公司下医院信息
            xDataSet.xDataSet mRetHospital = new xDataSet.xDataSet("Weixin_Interface_User", "dev",
                "getHospitalByCompanyUUID",
                new[] {new xParameter("uuid", companyUuid)}, Program.G_xDataSetConfigInterface)
                ;
            //判断返回值是否正确
            if (mRetHospital.SRetJObject["success"].ToString().ToLower() == "true")
            {
                //显示
                //cmb_province.Items.Add()
                var hospitalList =
                    JsonConvert.DeserializeObject<List<Hashtable>>(mRetHospital.SRetJObject["body"].ToString());
                return hospitalList;
            }
            return null;
        }

        protected override List<Hashtable> GetOfficeDataByHospital(string hospitaluuid)
        {
            xDataSet.xDataSet mRetOfficel = new xDataSet.xDataSet("Weixin_Interface_User", "dev",
                "getOfficMsgByHospUUID",
                new[] {new xParameter("uuid", hospitaluuid)}, Program.G_xDataSetConfigInterface)
                ;

            //判断返回值是否正确
            if (mRetOfficel.SRetJObject["success"].ToString().ToLower() == "true")
            {
                //显示
                //cmb_province.Items.Add()
                var mRetList =
                    JsonConvert.DeserializeObject<List<Hashtable>>(mRetOfficel.SRetJObject["body"].ToString());
                return mRetList;
            }
            return null;
        }
    }
}